using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Linq;
using System.Data.Linq.Mapping;

namespace ClubWebsite
{
    public partial class AddUser : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Enter QueryString parameters into the controls if they're provided
                if (Request.QueryString["Email"] != null)
                {
                    txtEmail.Text = HttpUtility.HtmlDecode(Request.QueryString["Email"].Trim());
                }
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // Validation
            litForgotPassword.Visible = false;
            valEmail.Validate();
            valPassword.Validate();
            if ((!valEmail.IsValid) || (!valPassword.IsValid))
            {
                return;
            }

            using (MainDataClassesDataContext databaseDataContext = Functions.GetDatabaseDataContext())
            {
                // Add the user (but don't save the row until the email is sent)
                User user = new User();
                user.ID = Guid.NewGuid();
                user.Email = txtEmail.Text.Trim();
                user.Password = txtPassword.Text.Trim();
                user.EmailConfirmationCode = RandomFunctions.CreateRandomCode(10);
                user.EmailConfirmed = 0;
                user.SiteAdministrator = 0;
                databaseDataContext.Users.InsertOnSubmit(user);

                // Send an email to the user with a confirmation code so that they can confirm
                // their email address
                try
                {
                    WebsiteEmail.SendEmailToConfirmEmailAddress(user.Email, user.EmailConfirmationCode);
                }
                catch (Exception ex)
                {
                    // Log the issue and let the user know there is a problem sending the email
                    Functions.WriteLogEntry("Exception", true, ex);
                    lblError.Text = "Could not verify the email address. Please ensure the email address is correct.<br /><br />Error: " + ex.Message;
                    lblError.Visible = true;
                    return;
                }

                // Save the new user
                databaseDataContext.SubmitChanges();

                // Go to the confirm email page
                Response.Redirect("../confirmregistration/Default.aspx?Email=" + HttpUtility.HtmlEncode(user.Email));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // Go back a page
            Response.Redirect(Request.UrlReferrer.ToString());
        }

        protected void valEmail_ServerValidate(object source, ServerValidateEventArgs args)
        {
            // Required
            if (txtEmail.Text.Trim().Length == 0)
            {
                valEmail.Text = "An entry is required";
                args.IsValid = false;
                return;
            }

            // Max length
            int maxLength = typeof(User).GetProperties()
                .Where(p => p.Name.ToLower() == "email")
                .Select(p => Functions.GetColumnSize((ColumnAttribute)p.GetCustomAttributes(typeof(ColumnAttribute), false).First()))
                .First();
            if (txtEmail.Text.Trim().Length > maxLength)
            {
                valEmail.Text = String.Format("The entry cannot be more than {0} characters", maxLength);
                args.IsValid = false;
                return;
            }

            // Valid email address format
            if (!WebsiteEmail.EmailAddressIsValid(txtEmail.Text.Trim()))
            {
                valEmail.Text = "Invalid email address format";
                args.IsValid = false;
                return;
            }

            // Unique
            bool emailExists = Functions.GetDatabaseDataContext()
                .Users
                .Any(u => u.Email.ToLower() == txtEmail.Text.Trim().ToLower());
            if (emailExists)
            {
                valEmail.Text = "This email is already registered.";
                valEmail.IsValid = false;
                litForgotPassword.Text = System.Text.RegularExpressions.Regex.Replace(litForgotPassword.Text, @"(?<=href="")\w*(?=\"")", "../forgotpassword/Default.aspx?Email=" + HttpUtility.HtmlEncode(txtEmail.Text.Trim()));
                litForgotPassword.Visible = true;
                return;
            }
        }

        protected void valPassword_ServerValidate(object source, ServerValidateEventArgs args)
        {
            // Required
            if (txtPassword.Text.Trim().Length == 0)
            {
                valPassword.Text = "An entry is required";
                args.IsValid = false;
                return;
            }

            // Max length
            int maxLength = typeof(User).GetProperties()
                .Where(p => p.Name.ToLower() == "password")
                .Select(p => Functions.GetColumnSize((ColumnAttribute)p.GetCustomAttributes(typeof(ColumnAttribute), false).First()))
                .First();
            if (txtPassword.Text.Trim().Length > maxLength)
            {
                valPassword.Text = String.Format("The entry cannot be more than {0} characters", maxLength);
                args.IsValid = false;
                return;
            }
        }
    }
}